<template>
  <div class="add-note-box">
    <van-nav-bar left-arrow>
      <template #left>
        <van-icon name="arrow-left" size="18" @click="goBack" />
      </template>
      <template #right>
        <van-icon name="success" size="18" @click="submitNote" />
      </template>
    </van-nav-bar>
    <van-field
      class="field"
      rows="1"
      autosize
      type="textarea"
      placeholder="请输入内容"
      v-model="state.note.content"
    ></van-field>
  </div>
</template>

<script setup lang="ts">
import { reactive, onMounted } from 'vue'
import { useListStore } from '@/stores/noteList'
import { showSuccessToast } from 'vant'
import { useRouter, useRoute } from 'vue-router'

const store = useListStore()
const state = reactive({
  note: {
    content: '',
    date: ''
  },
  oldContent: '',
  id: ''
})

const dateObj = new Date()
const router = useRouter()

const submitNote = () => {
  state.note.date = `${dateObj.getFullYear()} 年 ${dateObj.getMonth() + 1}月 ${dateObj.getDate()}日`
  if (state.id) {
    if (state.note.content !== state.oldContent) {
      const payload = { id: state.id, note: state.note }
      store.updateNote(payload).then((res) => {
        if (res) {
          showSuccessToast('更新成功')
          router.push('/')
        }
      })
    }
  } else {
    store.addNoteList(state.note).then((res) => {
      if (res) {
        showSuccessToast('添加成功')
        router.push('/')
      }
    })
  }
}

const goBack = () => {
  // window.history.back()
  router.go(-1)
  // router.back()
}

const route = useRoute()

const initNote = () => {
  const id = route.query.id
  if (!id) return
  store.list.forEach((item) => {
    if (item.id == id) {
      state.note.content = item.content
      state.oldContent = item.content
      state.id = id
    }
  })

  if (!store.list.length) {
    store.getNoteById(id as string).then((res) => {
      state.note.content = res.content
      state.oldContent = res.content
      state.note.date = res.date
      state.id = res.id as string
    })
  }
}

onMounted(() => {
  initNote()
})
</script>

<style lang="scss" scoped>
.add-note-box {
  width: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  flex: 1;
  background-color: #fff;
  .field {
    font-size: 0.22rem;
  }
}
</style>
